/**
 * Copyright © 2013 南京思创信息技术有限公司. *
 * 版权所有.
 *
 * 类名　　    : Login
 * 功能概要    : 登录页面. * 做成日期    : 2013/06/05 wangxw
 */
package com.sevenit.nj.yrmtfish.login;

import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.sevenit.nj.yrmtfish.R;
import com.sevenit.nj.yrmtfish.common.AppManager;
import com.sevenit.nj.yrmtfish.common.ServerMaster;
import com.sevenit.nj.yrmtfish.common.StaticPara;
import com.sevenit.nj.yrmtfish.common.Utils;
import com.sevenit.nj.yrmtfish.entity.ServerData;

/**
 * 登录页面的类
 * @author wangxw
 * @version 1.0
 */
@SuppressLint("HandlerLeak") 
public class Login extends Activity {
	
	//当面画面的名称
	private String _strPageName;
	
	//提示对话框.
	ProgressDialog _proDialog;
		
	//请求服务器方法
	private ServerMaster _server;
		
	/**
	 * onCreate
	 */
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		//自定义标题栏
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		//设置画面布局
		this.setContentView(R.layout.login);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		
		//添加该Activity到AppManager
		AppManager.addActivity(this);
		
		//设置画面控件
		setControl();

		//初始化画面数据.
		initPageData(); 
	}
	
	/**
	 * 设置画面控件
	 */
	private void setControl() {
		//设置标题文字
		TextView txtTitle = (TextView)findViewById(R.id.txt_title);
		txtTitle.setText(R.string.txt_login_title);
		//设置为粗体
		TextPaint paint = txtTitle.getPaint();
		paint.setFakeBoldText(true);
				
		//整个画面对象
		View loginView = (View)this.findViewById(R.id.login);
		loginView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				hiddenKeyPad();
				return false;
			}
		});
		
		//设置[返回]按钮按下效果
		ImageButton button = (ImageButton)findViewById(R.id.btn_back);
		button.setOnTouchListener(new ImageButton.OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
					arg0.setBackgroundResource(R.drawable.btn_back_p);
				} else if (arg1.getAction() == MotionEvent.ACTION_UP) {
					arg0.setBackgroundResource(R.drawable.btn_back);
				}
				return false;
			}
        });	
		//点击[返回]按钮的响应.
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				pageExit();
			}
		});
		
		//设置[登录]按钮按下效果
		button = (ImageButton)findViewById(R.id.btn_login);
		button.setOnTouchListener(new ImageButton.OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				if (arg1.getAction() == MotionEvent.ACTION_DOWN) {
					arg0.setBackgroundResource(R.drawable.btn_login_p);
				} else if (arg1.getAction() == MotionEvent.ACTION_UP) {
					arg0.setBackgroundResource(R.drawable.btn_login);
				}
				hiddenKeyPad();
				return false;
			}
        });	
		//点击[登录]按钮的响应.
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				doLogin();
			}
		});
	}
	
	/**
	 * 退出本画面.
	 */
	private void pageExit() {
		if(AppManager.getActCount() <= 1){
			//Intent intent = new Intent();
			//intent.setClass(Login.this, MainMenu.class);
			//startActivity(intent);
		}
		AppManager.closePage(Login.class.getName());
	}
	
	/**
	 * 初始化画面数据.
	 */
	private void initPageData() {
		
		_strPageName = this.getClass().getName();
		
		//初始化全局对象
		_server = new ServerMaster(this, StaticPara.MemConf.AppServerIp, StaticPara.MemConf.AppServerPort);
		
		//设置帐户的默认值
		String strCarNo = StaticPara.MemConf.CarNo;
		if(!Utils.isNull(strCarNo)){
			((EditText)findViewById(R.id.txt_car_no)).setText(strCarNo);
		}
	}

	/**
	 * 监听手机硬件上的返回等按钮
	 */
	@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_BACK &&	event.getRepeatCount() == 0) { 
        	pageExit();;
            return false; 
        }
        return false; 
    }
	
	/**
	 * 隐藏输入框.
	 */
	private void hiddenKeyPad() {
		//单击屏幕，软键盘自动隐藏.
		InputMethodManager mInputManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
		EditText txtCarNo = (EditText)findViewById(R.id.txt_car_no);
		EditText txtPassWord = (EditText)findViewById(R.id.txt_psw);
		mInputManager.hideSoftInputFromWindow(txtCarNo.getWindowToken(), 0);
		mInputManager.hideSoftInputFromWindow(txtPassWord.getWindowToken(), 0);
	}
	
	/**
	 * 登录处理.
	 */
	private void doLogin() {
		
		String strCarNo = ((EditText)findViewById(R.id.txt_car_no)).getText().toString().trim();
		String strPassword = ((EditText)findViewById(R.id.txt_psw)).getText().toString().trim();
		
		if(Utils.isNull(strCarNo)){
			Toast.makeText(Login.this, R.string.msg_carno_empty, Toast.LENGTH_LONG).show();
			return;
		}
		
		if(Utils.isNull(strPassword)){
			Toast.makeText(Login.this, R.string.msg_psw_empty, Toast.LENGTH_LONG).show();
			return;
		}
		
		//线程处理登录
		sendMsg(StaticPara.MSG_PAGE_LOADING);
	}
	
	/**
	 * 新线程查询数据.
	 * @author wangxw
	 */
	class LoadThread implements Runnable {
		
		public void run() {
			
			//登录处理
			String strCarNo = ((EditText)findViewById(R.id.txt_car_no)).getText().toString().trim();
			String strPassword = ((EditText)findViewById(R.id.txt_psw)).getText().toString().trim();
			
			Map<String, String> hMap = new HashMap<String, String>();
			hMap.put("GUID", StaticPara.MemConf.PhoneId);
			hMap.put("CarNumber", strCarNo);
			hMap.put("Password",strPassword);
			ServerData sd = _server.doRequest("UserLogin",hMap);

			if (sd.getStatus() == -1) {
				//当前网络不可用.
				sendMsg(StaticPara.MSG_ERR_NET);
			} else if (sd.getStatus() == -2) {
				//不能连接服务器，请稍候再试！
				sendMsg(StaticPara.MSG_ERR_SERVER);
			} else if (sd.getStatus() == -99){
				//未知的错误.
				sendMsg(StaticPara.MSG_ERR_UNKNOW);
			} else if (sd.getStatus() == 1){
				sd.first();
				String strRe = sd.getString("ReturnCode");
				if("00".equals(strRe)){
					//登录成功.
					sendMsg(StaticPara.MSG_PAGE_SHOW_DATA);
				} else if("01".equals(strRe) || "02".equals(strRe)){
					//错误的用户名或密码
					sendMsg(StaticPara.MSG_ERR_NODATA);
				} else {
					//未知的错误.
					sendMsg(StaticPara.MSG_ERR_UNKNOW);
				}
			}
		}
	}

	/**
	 * 向界面发送消息.
	 * UI显示动作不能在线程里做.
	 */
	private void sendMsg(int Msg){
		Message message = new Message();
		Bundle bundle = new Bundle();
		bundle.putInt(_strPageName, Msg);
		message.setData(bundle);
		myHandler.sendMessage(message);
	}
	
	//主线程消息处理.
	Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			int iMsg = msg.getData().getInt(_strPageName);
			switch (iMsg) {
			
			case StaticPara.MSG_ERR_NET:
				if (_proDialog != null) {
					_proDialog.dismiss();
				}
				Toast.makeText(Login.this, R.string.msg_net_error, Toast.LENGTH_LONG).show();
				break;
			case StaticPara.MSG_ERR_SERVER:
				if (_proDialog != null) {
					_proDialog.dismiss();
				}
				Toast.makeText(Login.this, R.string.msg_server_error, Toast.LENGTH_LONG).show();
				break;
			case StaticPara.MSG_ERR_UNKNOW:
				if (_proDialog != null) {
					_proDialog.dismiss();
				}
				Toast.makeText(Login.this, R.string.msg_unknown_error, Toast.LENGTH_LONG).show();
				break;
			case StaticPara.MSG_PAGE_LOADING:
				// 显示进度
				_proDialog = ProgressDialog.show(Login.this, "提示", "正在登录...", true, true);
				Thread loadThread = new Thread(new LoadThread());
				loadThread.start();
				break;
			case StaticPara.MSG_ERR_NODATA:
				// 登陆失败
				if (_proDialog != null) {
					_proDialog.dismiss();
				}
				Toast.makeText(Login.this, R.string.msg_name_psw_error, Toast.LENGTH_LONG).show();
				break;
			case StaticPara.MSG_PAGE_SHOW_DATA:
				// 登陆成功
				if (_proDialog != null) {
					_proDialog.dismiss();
				}
				StaticPara.MemConf.CarNo = ((EditText)findViewById(R.id.txt_car_no)).getText().toString().trim();
				StaticPara.MemConf.Password = ((EditText)findViewById(R.id.txt_psw)).getText().toString().trim();
				StaticPara.MemConf.UserSta = StaticPara.USER_STA_ONLINE;
				StaticPara.MemConf.saveMemConf();
				pageExit();
				break;
			default:
				if (_proDialog != null) {
					_proDialog.dismiss();
				}
			}
			
			super.handleMessage(msg);
		}
	};
}
